﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Batman.Cms.Core.Models.Mvc;
using Batman.Cms.Domains;
using Microsoft.EntityFrameworkCore;
using Senparc.Weixin.MP.CommonAPIs;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Cms.DomainServices
{
    public class WeixinMpAccountDomainService : DomainService
    {
        public IRepository<OpenAccount> Repository { get; set; }

        /// <summary>
        /// 验证数据库中是否存在appId或者serviceNo等于传入的值
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="serviceNo">服务号</param>
        /// <param name="id">编辑状态需要传入Id</param>
        /// <returns></returns>
        public ResponseBase IsUniq(string appId, string serviceNo, int? id = null)
        {
            var query = Repository.GetAll().AsNoTracking().Where(t => t.Platform == OpenAccountPlatform.微信);

            var found = query.FirstOrDefault(t => t.AppId == appId || t.ServiceNo == serviceNo);

            if (found == null) return new ResponseBase(true);

            if (id.HasValue)
            {
                if (found.AppId == appId && id.Value != found.Id)
                    return new ResponseBase(false, $"系统已存在appId等于{appId}的微信公众号资料");

                if (found.ServiceNo == serviceNo && id.Value != found.Id)
                    return new ResponseBase(false, $"系统已存在服务号等于{serviceNo}的微信公众号资料");
            }
            else
            {
                if (found.AppId == appId)
                    return new ResponseBase(false, $"系统已存在appId等于{appId}的微信公众号资料");

                if (found.ServiceNo == serviceNo)
                    return new ResponseBase(false, $"系统已存在服务号等于{serviceNo}的微信公众号资料");
            }

            return new ResponseBase(true);
        }

        /// <summary>
        /// 获取微信账号的AppId
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetWeixinAppId(int id)
        {
            var weixinMpAccount = Repository.GetAll().AsNoTracking().FirstOrDefault(t => t.Id == id);
            if (weixinMpAccount == null) return null;

            return weixinMpAccount.AppId;
        }

        /// <summary>
        /// 获取微信账号的Token
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<string> GetWeixinToken(int id)
        {
            var weixinMpAccount = Repository.GetAll().AsNoTracking().FirstOrDefault(t => t.Id == id);
            if (weixinMpAccount == null) return null;

            if (string.IsNullOrEmpty(weixinMpAccount.Token) || weixinMpAccount.ExpiredAt <= DateTime.Now)
            {
                var getTokenResult = await CommonApi.GetTokenAsync(weixinMpAccount.AppId, weixinMpAccount.Secret);
                if (string.IsNullOrEmpty(getTokenResult.errmsg))
                {
                    weixinMpAccount.Token = getTokenResult.access_token;
                    weixinMpAccount.ExpiredAt = DateTime.Now.AddSeconds(getTokenResult.expires_in);
                    Repository.Update(weixinMpAccount);
                }
            }

            return weixinMpAccount.Token;
        }
    }
}
